package downwebsite;



import java.io.*;
import java.net.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author MrKhoai
 */
public class Resource {
    private URL location = null;

    public Resource(String url) throws MalformedURLException {
        location = new URL(url);
    }

    public Resource(URL url) {
        location = url;
    }

    public InputStream getResource() throws IOException {
        BufferedInputStream reader = new BufferedInputStream(
                                     location.openStream());
        return reader;
    }

    public void writeResourceToFile(String dst) {

        String host = location.getHost();
        String path = location.getFile();
        path = path.replace('?', '@');
        path = path.replace('\\', '@');
        path = path.replace(':', '@');
        path = path.replace('*', '@');
        path = path.replace('<', '@');
        path = path.replace('>', '@');
        path = path.replace('|', '@');
        int index = path.lastIndexOf('/');
        if(index != -1) {
            String s = path.substring(0, index);
            File ff = new File(dst + host + s);
            if(!ff.exists()) {
                ff.mkdirs();
            }
        }
        try {
            File fout = new File(dst + host + path);
            if(fout.exists())
                return;
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fout));
            BufferedInputStream in = (BufferedInputStream)getResource();
            byte[] bytes = new byte[1024];
            int nbyte = in.read(bytes, 0, bytes.length);
            while(nbyte != -1) {
                out.write(bytes, 0, nbyte);
                nbyte = in.read(bytes, 0, bytes.length);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            return;
        }
    }
}
